package com.gaogzhen.controller;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaogzhen.domain.SysRole;
import com.gaogzhen.service.SysRoleService;
import com.gaogzhen.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Arrays;

/**
 * 角色管理控制器 * 1.查询
 *  1.1.分页查询
 * 2.新增
 * 3.修改
 * 4.删除
 * 角色管理的角色：
 * 1.查询: sys_role_query
 * 2.新增: sys_role_create
 * 3.修改: sys_role_update
 * 4.删除: sys_role_delete
 * @author Administrator
 */
@RestController
@RequestMapping("/roles")
@Api(tags = "角色管理器")
public class SysRoleController {
    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 根据角色名称模糊分页查询角色
     * @param page
     * @return
     */
    @GetMapping
    @ApiOperation("分页查询角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "size", value = "每页大小"),
            @ApiImplicitParam(name = "name", value = "角色名称")
    })
    @PreAuthorize("hasAuthority('sys_role_query')")
    public R<Page<SysRole>> findByPage(@ApiIgnore Page<SysRole> page, String name) {
        // 最新数据优先显示->修改时间逆序排序：lastUpdateTime
        page.addOrder(OrderItem.desc("last_update_time"));
        Page<SysRole> sysRolePage = sysRoleService.findByPage(page, name);
        return R.ok(sysRolePage);
    }

    /**
     * 新增角色
     * @param sysRole
     * @return
     */
    @PostMapping
    @ApiOperation(value = "新增角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysRole", value = "sysPrivilege的json数据")
    })
    @PreAuthorize("hasAuthority('sys_role_create')")
    public R add(@RequestBody @Validated SysRole sysRole) {
        // 信息补全：创建人-mybatisplus自动填充功能补全
        boolean save = sysRoleService.save(sysRole);
        if (save) {
            return R.ok();
        }
        return R.fail();
    }

    /**
     * 根据就是id批量删除角色
     * @param ids   角色id集合
     * @return
     */
    @DeleteMapping
    @ApiOperation(value = "批量删除角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "要删除的角色id集合")
    })
    @PreAuthorize("hasAuthority('sys_role_delete')")
    public R delete(@RequestBody String[] ids) {
        if (ArrayUtils.isEmpty(ids)) {
            return R.fail("要删除的数据不能为空！");
        }
        boolean b = sysRoleService.removeByIds(Arrays.asList(ids));
        if (b) {
            return R.ok();
        }
        return R.fail("删除失败！");
    }
}
